package com.yx.coredata.common.shiro;

import com.yx.coredata.module.user.domain.User;
import com.yx.coredata.module.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.crazycake.shiro.SerializeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * Created by lichagnfeng on 2017/2/9.
 */
@Service
public class PassRealm extends AuthorizingRealm {
    public final static Logger log = LoggerFactory.getLogger(AuthorizingRealm.class);
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    @Autowired
    private UserService userService;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug(" to doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = this.userService.findUserByUsername(username);
        if (user!=null) {
            Map<String, Object> mapUser = new HashMap<>();
            mapUser.put("id", user.getId());
            mapUser.put("userId", user.getId());
            mapUser.put("account", user.getAccount());
            mapUser.put("name", user.getName());
            mapUser.put("remark",user.getRemark());
            mapUser.put("role", user.getRole());
            mapUser.put("tel", user.getTel());
            mapUser.put("professionId", StringUtils.isEmpty(user.getProfessionId()) ? "" : user.getProfessionId() );

            mapUser.put("userPhoto", user.getUserPhoto());

            //将用户信息存入session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();

            session.setAttribute("user", SerializeUtils.serialize(mapUser));

            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), getName());

            return info;
        }else {
            return null;
        }
    }
}
